<?php
/**
 * Niushop商城系统 - 团队十年电商经验汇集巨献!
 * =========================================================
 * Copy right 2019-2029 杭州牛之云科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: https://www.niushop.com
 * =========================================================
 */

namespace addon\wechatpay\api\controller;

use addon\wechat\model\Config as WechatConfig;
use addon\wechatpay\model\Pay;
use addon\wechatpay\model\TransferConfig;
use app\exception\ApiException;
use app\model\member\Withdraw as MemberWithdraw;
use think\facade\Cache;
use think\facade\Log;
use app\api\controller\BaseApi;
use addon\weapp\model\Config as WeaAppConfig;
use addon\wechatpay\model\Config as WechatPayConfig;
use addon\memberwithdraw\model\Withdraw as WithdrawModel;
class Transfer extends BaseApi
{

    public function __construct()
    {
        parent::__construct();
    }


    /**
     * 微信转账v3用户主动收款回调
     */
    public function notify()
    {
        $pay = new Pay();
        $pay->transferNotify();
    }


    /**
     * 发起收款
     */

    public function transfer()
    {
        $id = $this->params['id'] ?? ''; //提现单id
        $transfer_type = $this->params['transfer_type'] ?? ''; //提现来源

        $configModel = new  TransferConfig();
        if (empty($transfer_type) || !array_key_exists($transfer_type, $configModel->from_type)) {
            return $this->response($this->error('', 'transfer_type参数有误'));
        }

        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);

        if (empty($id)) {
            return $this->response($this->error('', 'REQUEST_ID'));
        }

        $cache = Cache::get('transfer:' . $id);
        if (!empty($cache)) {
            return $this->response($this->error('', '系统处理中,请务重复提交'));
        }

        try {
            Cache::set("transfer:" . $id, 1, 10);
            $member_withdraw_model = new MemberWithdraw();
            $app_type = isset($this->params['app_type']) && $this->params['app_type'] == 'weapp' ? 1 : 0;
            $member_withdraw_model->updateMemberWithdrawPlatform($id,$this->member_id, $app_type); //判断是公众号还是小程序

            $result = (new withdrawModel())->transfer($id);
            Cache::delete('transfer:' . $id);

            return $this->response($result);
        } catch (ApiException $errorException) {
            Cache::delete('transfer:' . $id);
            Log::write('发起收款接口异常,原因' . $errorException->getMessage());
            return $this->response($this->error([], $errorException->getMessage()));
        }
    }

    /**
     * 撤销转账
     */

    public function cancel()
    {
        $out_trade_no = $this->params['out_trade_no'] ?? '';
        if (empty($out_trade_no)) {
            return $this->response($this->error('', '商户单号有误'));
        }
        $pay = new Pay();
        $result = $pay->transferCancel($out_trade_no);
        return $this->response($result);
    }


    /**
     * 获取转账配置
     */
    public function getWithdrawConfig()
    {
        $WechatPayConfig = new WechatPayConfig();
        $config = $WechatPayConfig->getPayConfig($this->site_id)['data']['value'];
        $wechat_config = (new WechatConfig())->getWechatConfig($this->site_id);
        $weapp_config_result = (new WeaAppConfig())->getWeappConfig($this->site_id);
        $data = [
            'transfer_type' => $config['transfer_type'] == 'v3' && $config['transfer_v3_type'] == $WechatPayConfig::TRANSFER_V3_TYPE_USER ? 1 : 0,
            'mch_id' => $config['mch_id'],
            'wechat_appid' => $wechat_config['data']['value']['appid'],
            'weapp_appid' => $weapp_config_result['data']['value']['appid']
        ];
        return $this->response($this->success($data));
    }


    /**
     * 更改状态为转账中
     */
    public function inProcess()
    {
        $id = $this->params['relate_tag'] ?? '';
        if(empty($id)){
            return $this->response($this->error('', 'REQUEST_ID'));
        }

        Log::write($id."变更状态为转账中");
        $transfer_model =  new MemberWithdraw();
        $transfer_info = $transfer_model->getMemberWithdrawInfo([ ['id', '=', $id]])['data'];
        $res = $transfer_model->updateStatus(['status' => $transfer_model::STATUS_IN_PROCESS], $transfer_info['id'] ?? 0);
        return $this->response($res);
    }


}